//
//  my_fankui.m
//  HappyStore
//
//  Created by 点点充 on 16/1/25.
//  Copyright © 2016年 LLJ. All rights reserved.
//

#import "my_fankui.h"

@interface my_fankui ()
{
    NSMutableArray *muArySaveImg;
}
@end

@implementation my_fankui

- (void)viewDidLoad {
    [super viewDidLoad];
    
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 190, 44)];
    titleLabel.backgroundColor = [UIColor clearColor];
    titleLabel.font = [UIFont systemFontOfSize:19];
    titleLabel.text = @"反馈";
    titleLabel.textColor = [UIColor whiteColor];
    titleLabel.textAlignment = NSTextAlignmentCenter;
    self.navigationItem.titleView = titleLabel;
    
    //设置返回按钮
    UIBarButtonItem *leftItem = [UIBarButtonItem itemWithTarget:self action:@selector(leftBarButtonItemClick) image:@"Back" highImage:@"Back"];
    self.navigationItem.leftBarButtonItem = leftItem;
    
    
    muArySaveImg = [NSMutableArray arrayWithObject:[UIImage imageNamed:@"re_project_add2"]];
    _mainTextView.textColor = [UIColor colorWithWhite:0.75 alpha:1.f];
    _mainTextView.text = @"请输入您宝贵的意见";
    
    _btnTiJiao.layer.masksToBounds = YES;
    _btnTiJiao.layer.cornerRadius = 5.f;
    
    _mainTextView.layer.masksToBounds = YES;
    _mainTextView.layer.cornerRadius = 5.f;
    _mainTextView.layer.borderColor = [UIColor colorWithRed:201/255.0f green:202/255.0f blue:202/255.0f alpha:1.0f].CGColor;
    _mainTextView.layer.borderWidth = 0.5f;
    
    //开启侧滑
    self.navigationController.interactivePopGestureRecognizer.delegate = (id)self;
    
}
-(void)leftBarButtonItemClick{
    [self.navigationController popViewControllerAnimated:YES];
}
- (BOOL)textViewShouldBeginEditing:(UITextView *)textView
{
    if ([textView.text isEqualToString:@"请输入您宝贵的意见"]) {
        textView.text = @"";
        textView.textColor = [UIColor colorWithRed:137/255.0f green:137/255.0f blue:137/255.0f alpha:1.0f];
    }
    
    return YES;
}

- (void)textViewDidEndEditing:(UITextView *)textView
{
    if (textView.text.length == 0) {
        textView.text = @"请输入您宝贵的意见";
        textView.textColor = [UIColor colorWithWhite:0.75 alpha:1.f];
    }
    
}

#pragma mark- UICollectionViewDelegate
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}
//个数
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return muArySaveImg.count;
    
}
//行内容
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    
    static NSString *cell1 = @"cell1";
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cell1 forIndexPath:indexPath];
    
    //    NSLog(@"子视图:%@",cell.subviews);
    
    UIButton *btnImage = [cell viewWithTag:10];
    btnImage.layer.masksToBounds = YES;
    btnImage.layer.cornerRadius = 5.f;
    [btnImage setImage:muArySaveImg[indexPath.row] forState:UIControlStateNormal];
    [btnImage addTarget:self action:@selector(btnClickAddImage:) forControlEvents:UIControlEventTouchUpInside];
    btnImage.hidden = NO;
    btnImage.userInteractionEnabled = YES;
    
    UIButton *btnDelete = [cell viewWithTag:11];
    btnDelete.hidden = NO;
    [btnDelete addTarget:self action:@selector(btnClickDeleteImage:) forControlEvents:UIControlEventTouchUpInside];
    
    //    NSLog(@"子视图:%@",btnDelete.superview);
    
    if (muArySaveImg.count == 1 || indexPath.row == muArySaveImg.count-1) {
        btnDelete.hidden = YES;
    }else {
        btnImage.userInteractionEnabled = NO;
    }
    
    if (muArySaveImg.count == 6 && indexPath.row == muArySaveImg.count -1) {
        btnImage.hidden = YES;
        btnDelete.hidden = YES;
    }
    
    
    
    return cell;
}

#pragma mark - 添加5张图片
- (void)btnClickAddImage:(UIButton *)sender
{
    UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:@"照片选择"
                                                             delegate:self
                                                    cancelButtonTitle:@"取消"
                                               destructiveButtonTitle:nil
                                                    otherButtonTitles:@"相机",@"相册", nil];
    actionSheet.tag = 333;
    [actionSheet showInView:self.view];
}

#pragma mark - 选择照片
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    //先设定sourceType为相机，然后判断相机是否可用（ipod）没相机，不可用将sourceType设定为相片库
    UIImagePickerController *pickerImage = [[UIImagePickerController alloc] init];
    pickerImage.delegate = self;
    pickerImage.allowsEditing = YES;//设置可编辑
    switch (buttonIndex) {
        case 0:
        {
            NSLog(@"相机");
            pickerImage.sourceType = UIImagePickerControllerSourceTypeCamera;
            [self presentViewController:pickerImage animated:YES completion:nil];//进入照相界面
        }
            break;
        case 1:
        {
            NSLog(@"相册");
            pickerImage.sourceType = UIImagePickerControllerSourceTypePhotoLibrary; //图片库
            [self presentViewController:pickerImage animated:YES completion:nil];//进入照相界面
        }
            break;
        case 2:
        {
            NSLog(@"取消");
        }
            break;
    }
    
}

//点击相册中的图片 货照相机照完后点击use  后触发的方法
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    [picker dismissViewControllerAnimated:YES completion:^{}];
    
    UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage];
    //    [_btnUserImg setImage:image forState:UIControlStateNormal];
    //    _btnUserImg.layer.masksToBounds = YES;
    //    _btnUserImg.layer.cornerRadius = 20.0;
    /* 此处info 有六个值
     * UIImagePickerControllerMediaType; // an NSString UTTypeImage)
     * UIImagePickerControllerOriginalImage;  // a UIImage 原始图片
     * UIImagePickerControllerEditedImage;    // a UIImage 裁剪后图片
     */
    // 保存图片至本地，方法见下文
    //    NSString *strName = [NSString stringWithFormat:@"%@.jpg",[self dateString]];
    //    [self saveImage:image withName:strName];
    
    //5张详情 图片
    [muArySaveImg insertObject:image atIndex:0];
    if (muArySaveImg.count == 2) {
        [muArySaveImg replaceObjectAtIndex:1 withObject:[UIImage imageNamed:@"re_project_add3"]];
    }
    
    [_mainCollection reloadData];
    
}

//点击cancel 调用的方法
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [picker dismissViewControllerAnimated:YES completion:^{}];
}

#pragma mark - 保存图片至沙盒
- (void) saveImage:(UIImage *)currentImage withName:(NSString *)imageName
{
    NSData *imageData = UIImageJPEGRepresentation(currentImage, 0.1);
    // 获取沙盒目录
    NSString *fullPath = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:imageName];
    // 将图片写入文件
    [imageData writeToFile:fullPath atomically:NO];
}

#pragma mark - 删除5张图片
- (void)btnClickDeleteImage:(UIButton *)sender
{
    UIView *viewContent = sender.superview;
    
    NSIndexPath *indexPath = [_mainCollection indexPathForCell:(UICollectionViewCell *)viewContent.superview];
    NSLog(@"--------%ld",indexPath.row);
    [muArySaveImg removeObjectAtIndex:indexPath.row];
    
    [_mainCollection reloadData];
    
}


#pragma mark 照片的时间名称
- (NSString*)dateString
{
    NSMutableString*string=[[NSMutableString alloc] init];
    NSDate*dayDate=[NSDate date];
    NSDateFormatter*dayFormatter=[[NSDateFormatter alloc] init];
    [dayFormatter setDateFormat:@"yyyy-MM-dd"];
    NSString *dateStrings= [dayFormatter stringFromDate:dayDate];
    NSArray*dayArray=[dateStrings componentsSeparatedByString:@"-"];
    for (int i=0; i<[dayArray count]; i++) {
        [string appendFormat:@"%@",[dayArray objectAtIndex:i]];
    }
    NSDate*timeDate=[NSDate date];
    NSDateFormatter*timeFormatter=[[NSDateFormatter alloc] init];
    [timeFormatter setDateFormat:@"HH:mm:ss:SSS"];
    NSString *timeString= [timeFormatter stringFromDate:timeDate];
    NSArray*timeArray=[timeString componentsSeparatedByString:@":"];
    for (int i=0; i<[timeArray count]; i++) {
        [string appendFormat:@"%@",[timeArray objectAtIndex:i]];
    }
    return string;
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - 提交
- (IBAction)btnClickTijiao:(id)sender
{
    BOOL isOK = YES;
    if ([_mainTextView.text isEqualToString:@"请输入您宝贵的意见"] || _mainTextView.text.length == 0) {
        isOK = NO;

        [self showSingleIconBubble:@"请输入您宝贵的意见"];
    }
    
    
    if (isOK) {
        //token=rE3F2m8AvfC7CVh85O9q&userId=10&content=反馈原因 参数说明：photos-为图片zip包
        [self showRoundProgressWithTitle:@"请稍后..."];
        NSMutableDictionary *muDicParameters = [NSMutableDictionary dictionary];
        [muDicParameters setObject:[USER_DEFAULTS objectForKey:@"token"] forKey:@"token"];//验证用户
        [muDicParameters setObject:[USER_DEFAULTS objectForKey:@"userid"] forKey:@"userId"];
        
        
        NSString *strURl = [NSString stringWithFormat:@"%@%@",URL_DEFINE,@"addFeedback_app_myHome.im.lensum"];
        
        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        
        [manager POST:strURl parameters:muDicParameters constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
            
            // 压缩
            NSMutableArray *aryImg = [NSMutableArray arrayWithArray:muArySaveImg];
            NSMutableArray *muSaveFull = [NSMutableArray array];
            [aryImg removeLastObject];
            for (int i = 0; i<aryImg.count; i++) {
                UIImage *image = aryImg[i];
                NSString *strName1 = [NSString stringWithFormat:@"%@.png",[self dateString]];
                [self saveImage:image withName:strName1];
                NSString *fullPath1 = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:strName1];
                [muSaveFull addObject:fullPath1];
            }
            
            
            NSString *zippedPath = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.zip",[self dateString]]];
            
            BOOL isSucee = [SSZipArchive createZipFileAtPath:zippedPath withFilesAtPaths:muSaveFull];
            if (isSucee) {
                NSData *data1 = [NSData dataWithContentsOfFile:zippedPath];
                [formData appendPartWithFileData:data1 name:@"photos" fileName:@"photos.zip" mimeType:@"zip"];
            }
            
        } progress:^(NSProgress * _Nonnull uploadProgress) {
            
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            NSDictionary *dicInfo = [NSDictionary dictionaryWithDictionary:responseObject];
//            NSLog(@"%@",dicInfo);

            if ([dicInfo[@"result"] integerValue] == 1) {
                [self performSelector:@selector(btnClickDismiss) withObject:nil afterDelay:kHideHudDelay];

                [self showRightWithTitle:dicInfo[@"msg"] autoCloseTime:2];
            }else {

                [self showSingleIconBubble:dicInfo[@"msg"]];
            }

        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {

           [self showSingleIconBubble:error.localizedDescription];

        }];
        
    }
}

- (void)btnClickDismiss
{
    [self.navigationController popViewControllerAnimated:YES];
}

@end
